package com.ruoyi.platform.listener;

import com.ruoyi.common.annotation.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description 监听服务类
 * @author:Figo2020
 * @date: 2025/10/25 23:10
 */
public class TcpListenerServer implements ApplicationListener<ContextRefreshedEvent> {
    
    private final int port;
    private ServerSocket serverSocket;
    private ExecutorService threadPool;
    private volatile boolean running = false;
    
    public TcpListenerServer(int port) {
        this.port = port;
    }
    
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        startServer();
    }
    
    public void startServer() {
        try {
            serverSocket = new ServerSocket(port);
            threadPool = Executors.newFixedThreadPool(10); // 线程池处理并发连接
            running = true;
            
            System.out.println("TCP服务器已启动，监听端口: " + port);
            
            // 启动监听线程
            new Thread(this::acceptConnections).start();
            
        } catch (IOException e) {
            System.err.println("启动TCP服务器失败: " + e.getMessage());
        }
    }
    
    private void acceptConnections() {
        while (running) {
            try {
                Socket clientSocket = serverSocket.accept();
                System.out.println("新的客户端连接: " + clientSocket.getInetAddress().getHostAddress());
                
                // 提交到线程池处理
                threadPool.submit(new ClientHandler(clientSocket));
                
            } catch (IOException e) {
                if (running) {
                    System.err.println("接受连接时出错: " + e.getMessage());
                }
            }
        }
    }
    
    public void stopServer() {
        running = false;
        try {
            if (serverSocket != null) {
                serverSocket.close();
            }
            if (threadPool != null) {
                threadPool.shutdown();
            }
            System.out.println("TCP服务器已停止");
        } catch (IOException e) {
            System.err.println("停止服务器时出错: " + e.getMessage());
        }
    }
    
    private static class ClientHandler implements Runnable {
        private final Socket clientSocket;
        
        public ClientHandler(Socket socket) {
            this.clientSocket = socket;
        }
        
        @Override
        public void run() {
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(clientSocket.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder jsonBuilder = new StringBuilder();
                String receivedData;
                while ((receivedData = reader.readLine()) != null) {
                    // 解析和处理数据
                    jsonBuilder.append(receivedData);
                    if (receivedData.trim().endsWith("}")) {
                        break;
                    }
                }
                DataParser.parseAndProcess(jsonBuilder.toString(), clientSocket.getInetAddress().toString());
            } catch (IOException e) {
                System.err.println("处理客户端数据时出错: " + e.getMessage());
            } finally {
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    System.err.println("关闭客户端连接时出错: " + e.getMessage());
                }
            }
        }
    }
}
